package com.gouda.temporary.controller;

import com.gouda.temporary.context.ContextCode;
import com.gouda.temporary.service.TempHourOrdersService;
import com.gouda.temporary.service.WeiXinService;
import com.gouda.temporary.utils.*;
import com.gouda.temporary.vo.TempHourOrders;
import com.gouda.temporary.vo.openwx.UserInfoWithCode;
import com.gouda.temporary.vo.openwx.WxOwnerInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.PrintWriter;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;

@Controller
@RequestMapping(value = "/temp")
public class OwnerController {

    private static final Logger log = LoggerFactory.getLogger(OwnerController.class);

    @Resource
    private TempHourOrdersService tempHourOrdersService;

    @Resource
    private WeiXinService weiXinService;

    @ModelAttribute
    public void init(ModelMap model, HttpServletRequest request) {
        model.put("ctx", request.getContextPath());
    }

    /**
     * 业主创建订单的表单页
     *
     * @param request 微信业主下单对的信息回调
     * @return 业主填单页面
     */
    @RequestMapping(value = "/orders-form")
    public String navigateToOwnerOrders(HttpServletRequest request, Model model) {
        // 获取微信回调信息参数
        String code = request.getParameter("code");
        String state = request.getParameter("state");

        log.info(">>>> 业主下单 code={}, state={}", code, state);

        // 通过微信接口获取业主信息
        WxOwnerInfo wxOwnerInfo = weiXinService.takeOwnerInfo(code);
        if (!ContextCode.WX_OK.equals(wxOwnerInfo.getErrcode())) {
            // TODO 下单失败页没有
        }

        log.info(">>>> 业主信息:" + wxOwnerInfo);

        // 将业主信息传到 订单页
        model.addAttribute("userid", wxOwnerInfo.getUserid());
        model.addAttribute("name", wxOwnerInfo.getName());
        model.addAttribute("mobile", wxOwnerInfo.getMobile());

        return "owner_order_form";
    }

    /**
     * 保存业主订单信息
     */
    @RequestMapping(value = "/orders-save")
    @ResponseBody
    public Map<String, String> ownerOrdersSave(TempHourOrders tempHourOrders) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            String now = CommonUtils.getNow();
            tempHourOrders.setCreateDate(now);
            tempHourOrders.setOrderStatus(0);
            tempHourOrders.setOrderNo(CommonUtils.genOrderId());
            this.tempHourOrdersService.saveTempHourOrders(tempHourOrders);

            // 给小时工发群发消息
            String xsTitle = "您有一个新的任务，快来抢吧～～";
            String xsDescription = buildLss(tempHourOrders.getOwnerMessage()) +
                    "\n\n派单时间: " + now;
            String xsUrl = buildsxUrl(tempHourOrders.getOrderNo());
            String partId = "5"; // 部门ID-物业小时工
            weiXinService.sendNewsMsgToPartID(partId, xsTitle, xsDescription, xsUrl);

            // 给业主发送订单发布成功的消息
            String title = "任务已经发布";
            String description = "任务编号: " + tempHourOrders.getOrderNo() + "\n派单时间: " + now;
            String url = "http://gouda3.xinleju.cn:8080/gouda-jm/temp/order-detail.do?userType=1&orderId=" + tempHourOrders.getOrderNo();
            weiXinService.sendNewsMsgToOwner(tempHourOrders.getOwnerId(), title, description, url);

            map.put("success", "1");
        } catch (Exception e) {
            log.error("", e);
            map.put("success", "0");
        }

        return map;
    }

    private String buildLss(String message) {
        if (message == null) {
            return "";
        }

        String temp;
        int len = message.length();
        if (message.length() > 30) {
            temp = message.substring(0, 28);
            temp += ".....";
            return temp;
        } else {
            return message;
        }
    }

    private String buildsxUrl(String orderId) {
        return "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=wx6a3274ac5b596aea&" +
                "redirect_uri=http%3a%2f%2fgouda3.xinleju.cn%3a8080%2fgouda-jm%2ftemp%2fworker-get-url.do?orderId=" + orderId + "&" +
                "response_type=code&" +
                "scope=snsapi_base&" +
                "state=STATE#" +
                "wechat_redirect";
    }

    /**
     * 业主查询订单列表-非安全方式
     */
    @RequestMapping(value = "/orders-list")
    public ModelAndView ownerOrderList(String ownerId, String userType) {
        Map<String, Object> map = new HashMap<String, Object>();
        //type： 1 业主; 2 小时工
        if (userType.equals("1")) {
            List<TempHourOrders> lorder = this.tempHourOrdersService.getTempHourOrdersByOwnerId(ownerId);
            map.put("olist", lorder);
        } else if (userType.equals("2")) {
            List<TempHourOrders> lorder = this.tempHourOrdersService.getTempHourOrdersByWorkerId(ownerId);
            map.put("olist", lorder);
        }
        map.put("userType", userType);
        return new ModelAndView("orderlist", map);
    }


    /**
     * 点击自定义菜单列表'任务列表' (业主查询订单列表-微信安全链接方式)
     */
    @RequestMapping(value = "/orders-list-safe")
    public ModelAndView ownerOrderListSafe(HttpServletRequest request) {
        /* 确定用户身份 */
        String code = request.getParameter("code");
        WxOwnerInfo wxOwnerInfo = weiXinService.takeOwnerInfo(code);

        if (ContextCode.WX_OK.equals(wxOwnerInfo.getErrcode())) {
            request.getSession().setAttribute("wxUserInfo", wxOwnerInfo);
        } else {
            wxOwnerInfo = (WxOwnerInfo) request.getSession().getAttribute("wxUserInfo");
        }

        log.info(">>>> 通过code获取用户信息: code={}, userInfo={}", code, wxOwnerInfo);

        return ownerOrderList(wxOwnerInfo.getUserid(), "1");//userType=1 表示业主
    }

    /**
     * 订单详情
     */
    @RequestMapping(value = "/order-detail")
    public ModelAndView ownerCommitOrder(HttpServletRequest request, HttpServletResponse response) {
        String orderid = request.getParameter("orderId");
        String userType = request.getParameter("userType");

        TempHourOrders tempHourOrders = this.tempHourOrdersService.getTempHourOrdersByOrderNo(orderid);
        if (tempHourOrders == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order", tempHourOrders);
        map.put("userType", userType);
        return new ModelAndView("orderdetail", map);
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////// 神奇分割线,一起下全是'小时工抢单'功能实现

    /**
     * 小时工-快速抢单(通过微信的自定义菜单'快速抢单')
     */
    @RequestMapping(value = "/worker-get")
    public ModelAndView workerGetOrder(HttpServletRequest request, Model model) {
        // 获取微信回调信息参数
        String code = request.getParameter("code");
        String state = request.getParameter("state");

        // 通过微信接口获取'小时工信息'
        WxOwnerInfo userInfo = weiXinService.takeOwnerInfo(code);
        String workerId = userInfo.getUserid();
        String workerName = userInfo.getName();
        String workerPhone = userInfo.getMobile();
        Map<String, Object> map = new HashMap<String, Object>();
        if (!ContextCode.WX_OK.equals(userInfo.getErrcode())) {
            map.put("success", "0");
        } else {
            TempHourOrders newsTempHourOrder = this.tempHourOrdersService.getNewsTempHourOrder();
            if (newsTempHourOrder != null) {
                newsTempHourOrder.setWorkerId(workerId);
                newsTempHourOrder.setWorkerName(workerName);
                newsTempHourOrder.setWorkerPhone(workerPhone);
                map.put("order", newsTempHourOrder);
                map.put("success", "1");
            } else {
                map.put("success", "2");
            }
        }
        log.info(">>>> 小时工信息-自定义菜单: code={}, state={}, userInfo={} ", code, state, userInfo);
        return new ModelAndView("orderdetail2", map);
    }

    /**
     * 小时工抢单-通过推送的消息
     */
    @RequestMapping(value = "/worker-get-url")
    public ModelAndView orderGetOrderUrl(HttpServletRequest request) {
        // 获取微信回调信息参数
        String code = request.getParameter("code");
        String state = request.getParameter("state");

        // 通过微信接口获取小时工信息
        WxOwnerInfo userInfo = weiXinService.takeOwnerInfo(code);
        if (!ContextCode.WX_OK.equals(userInfo.getErrcode())) {
            return new ModelAndView("orderdetail2");
        }

        String workerId = userInfo.getUserid();
        String workerName = userInfo.getName();
        String workerPhone = userInfo.getMobile();

        String orderid = request.getParameter("orderId");
        TempHourOrders tempHourOrders = this.tempHourOrdersService.getTempHourOrdersByOrderNo(orderid);

        if (tempHourOrders == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Integer orderStatus = tempHourOrders.getOrderStatus();
        if (orderStatus != 0) {
            map.put("success", "0");
            tempHourOrders.setWorkerId(workerId);
            tempHourOrders.setWorkerName(workerName);
            tempHourOrders.setWorkerPhone(workerPhone);
            map.put("order", tempHourOrders);
        } else {
            map.put("success", "1");
            tempHourOrders.setWorkerId(workerId);
            tempHourOrders.setWorkerName(workerName);
            tempHourOrders.setWorkerPhone(workerPhone);
            map.put("order", tempHourOrders);
        }

        return new ModelAndView("orderdetail2", map);
    }

    @RequestMapping(value = "worker-order-list")
    public ModelAndView showWorkerOrders(HttpServletRequest request) {
        // 获取微信回调信息参数
        String code = request.getParameter("code");

        // 通过微信接口获取小时工信息
        WxOwnerInfo userInfo = weiXinService.takeOwnerInfo(code);

        if (ContextCode.WX_OK.equals(userInfo.getErrcode())) {
            request.getSession().setAttribute("wxUserInfo", userInfo);
        } else {
            userInfo = (WxOwnerInfo) request.getSession().getAttribute("wxUserInfo");
        }

        return workerTaskList(userInfo.getUserid());
    }

    /**
     * 小时工查询任务列表-非安全方式
     */
    public ModelAndView workerTaskList(String workerId) {
        List<TempHourOrders> workerTaskList = this.tempHourOrdersService.getTempHourOrdersByWorkerId(workerId);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("olist", workerTaskList);
        map.put("userType", "2");
        return new ModelAndView("orderlist", map);
    }

    /**
     * 小时工抢单-orderdetail2.jsp里面的'抢单'按钮
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/worker-snatch")
    @ResponseBody
    public Map<String, String> snatchOrders(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();

        String workerId = request.getParameter("workerId");
        String workerName = request.getParameter("workerName");
        String workerPhone = request.getParameter("workerPhone");
        String order_no = request.getParameter("orderId");

        TempHourOrders tempHourOrders = this.tempHourOrdersService.getTempHourOrdersByOrderNo(order_no);

        String ownerId = tempHourOrders.getOwnerId();
        String orderNo = tempHourOrders.getOrderNo();
        String createDate = tempHourOrders.getCreateDate();
        String ownerMsg = tempHourOrders.getOwnerMessage();

        // 根据workerId和order_no >>>> select update 更新订单信息
        TempHourOrders fromSet = new TempHourOrders();
        fromSet.setOrderNo(order_no);
        fromSet.setWorkerId(workerId);
        fromSet.setOrderStatus(1);
        fromSet.setAcceptDate(CommonUtils.getNow());
        fromSet.setWorkerId(workerId);
        fromSet.setWorkerName(workerName);
        fromSet.setWorkerPhone(workerPhone);

        int un = this.tempHourOrdersService.updateOrderStatus(fromSet);
        if (un <= 0) { // 抢单失败
            sendWorkerSnatchFail(workerId, orderNo, ownerMsg, createDate);// 对小时发送抢单失败
            map.put("success", "0");
        } else {
            sendWorkerSnatchSuccess(workerId, orderNo, ownerMsg, createDate);// 对小时工发送抢单成功
            sendOwnerSnatchSuccess(ownerId, orderNo, createDate); // 对业主发送订单被抢
            map.put("success", "1");
        }
        return map;
    }

    private void sendWorkerSnatchFail(String workerId, String orderNo, String ownerMessage, String createDate) {
        String title = "抢单失败";
        String xsDescription = buildLss(ownerMessage) + "\n\n派单时间: " + createDate;
        String url = "http://gouda3.xinleju.cn:8080/gouda-jm/temp/order-detail.do?userType=2&orderId=" + orderNo;
        weiXinService.sendNewsMsgToWorker(workerId, title, xsDescription, url);
    }

    private void sendWorkerSnatchSuccess(String workerId, String orderNo, String ownerMessage, String createDate) {
        String title = "抢单成功";
        String xsDescription = buildLss(ownerMessage) + "\n\n派单时间: " + createDate;
        String url = "http://gouda3.xinleju.cn:8080/gouda-jm/temp/order-detail.do?userType=2&orderId=" + orderNo;
        weiXinService.sendNewsMsgToWorker(workerId, title, xsDescription, url);
    }

    private void sendOwnerSnatchSuccess(String ownerId, String orderNo, String createDate) {
        String title = "任务已被接受";
        String description = "任务编号: " + orderNo + "\n派单时间: " + createDate;
        String url = "http://gouda3.xinleju.cn:8080/gouda-jm/temp/order-detail.do?userType=1&orderId=" + orderNo;
        weiXinService.sendNewsMsgToOwner(ownerId, title, description, url);
    }

    @RequestMapping(value = "/wuyehongbao")
    public void wuyehongbao(HttpServletRequest request,HttpServletResponse response) throws IOException{
        String sToken = "VT2nOnlZC9V15Bst9BbaEXq0Jd";
        String sCorpID = "wx6a3274ac5b596aea";
        String sEncodingAESKey = "JgrQJqWOL0UBjIyoc1tJ8V1XxdA2MQjj7BzDQ4QjavI";
        // 微信加密签名
        String sVerifyMsgSig =  request.getParameter("msg_signature");
        // 时间戳
        String sVerifyTimeStamp = request.getParameter("timestamp");
        // 随机数
        String sVerifyNonce = request.getParameter("nonce");
        // 随机字符串
        String sVerifyEchoStr = request.getParameter("echostr");
        String sEchoStr="";
        // 需要返回的明文
        log.info("sToken:" + sToken);
        log.info("sCorpID:" + sCorpID);
        log.info("sEncodingAESKey:" + sEncodingAESKey);
        log.info("msg_signature:" + sVerifyMsgSig);
        log.info("timestamp:" + sVerifyTimeStamp);
        log.info("nonce:" + sVerifyNonce);
        log.info("echostr:" + sVerifyEchoStr);
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        log.info("postData:"+sb.toString());
        PrintWriter out = response.getWriter();
        WXBizMsgCrypt wxcpt;

        try {
            wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
            sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,
                    sVerifyNonce, sVerifyEchoStr);
            log.info("verifyurl echostr: " + sEchoStr);
            // 验证URL成功，将sEchoStr返回
            out.print(sEchoStr);
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
    }
}

